package com.suep.game_chat.controller;

import com.suep.game_chat.dto.UserDTO;
import com.suep.game_chat.dto.UserDTOLogin;
import com.suep.game_chat.entity.User;
import com.suep.game_chat.service.UserService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户管理控制器
 * 处理用户注册、登录和密码修改等基本功能
 *
 * @author Game Chat Team
 * @version 1.0
 */
@RestController
@RequestMapping("/api/users")
@CrossOrigin(origins = "*")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 用户注册接口
     * 处理新用户的注册请求，创建新的用户账号
     *
     * @param userDTO 用户注册信息，包含用户名、密码等必要信息
     * @return ResponseEntity 包含注册成功信息和用户基本信息
     * @throws jakarta.validation.ValidationException 当提供的用户信息不符合验证规则时
     */
    @PostMapping("/register")
    public ResponseEntity<?> register(@Valid @RequestBody UserDTO userDTO) {
        User user = userService.register(userDTO);
        Map<String, Object> response = new HashMap<>();
        response.put("message", "注册成功");
        response.put("userId", user.getUserId());
        response.put("username", user.getUsername());
        response.put("nickname", user.getNickname());
        return ResponseEntity.ok(response);
    }

    /**
     * 用户登录接口
     * 验证用户身份并处理登录请求
     *
     * @param userDTO 登录信息，包含用户名和密码
     * @return ResponseEntity 包含登录成功信息和用户详细信息
     * @throws RuntimeException 当用户名或密码错误时
     */
    @PostMapping("/login")
    public ResponseEntity<?> login(@Valid @RequestBody UserDTOLogin userDTO) {
        User user = userService.login(userDTO.getUsername(), userDTO.getPassword());
        Map<String, Object> response = new HashMap<>();
        response.put("message", "登录成功");
        response.put("userId", user.getUserId());
        response.put("username", user.getUsername());
        response.put("nickname", user.getNickname());
        response.put("avatar", user.getAvatar());
        response.put("level", user.getLevel());
        response.put("experience", user.getExperience());
        return ResponseEntity.ok(response);
    }

    /**
     * 修改密码接口
     * 允许用户修改其账号密码
     *
     * @param userId 用户ID
     * @param oldPassword 原密码
     * @param newPassword 新密码
     * @return ResponseEntity 包含密码修改成功的确认信息
     * @throws RuntimeException 当原密码验证失败或新密码不符合要求时
     */
    @PostMapping("/{userId}/password")
    public ResponseEntity<?> updatePassword(
            @PathVariable String userId,
            @RequestParam String oldPassword,
            @RequestParam String newPassword) {
        userService.updatePassword(userId, oldPassword, newPassword);
        Map<String, Object> response = new HashMap<>();
        response.put("message", "密码修改成功");
        return ResponseEntity.ok(response);
    }
}
